package com.cc.openeye.base.network

import com.cc.openeye.base.network.RequestHeaderManager.pingCommonHead
import com.tencent.kuikly.core.manager.PagerManager
import com.tencent.kuikly.core.module.NetworkModule
import com.tencent.kuikly.core.module.NetworkResponse
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import kotlinx.serialization.json.Json
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine


suspend inline fun <reified T> get(
    url: String,
    param: JSONObject = JSONObject(),
    headers: JSONObject = JSONObject()
): Response<T> {
    val networkModule = acquireNetworkModule()
    return suspendCoroutine { coroutine ->
        networkModule.httpRequest(
            url,
            false,
            param,
            pingCommonHead(headers),
            responseCallback = { json, isSuccess, errorMsg, response ->
                val obj = createResponse<T>(isSuccess, errorMsg, response)

                val lenientJson = Json {
                    ignoreUnknownKeys = true // 忽略 JSON 中存在的但数据类中未定义的字段
                    coerceInputValues = true // 尝试强制转换类型不匹配的值
                    isLenient = true // 允许更宽松的 JSON 格式（如单引号、不带引号的键）
                }

                if (isSuccess) obj.data = lenientJson.decodeFromString<T>(json.toString())
                coroutine.resume(obj)
            })
    }
}

fun <T> createResponse(
    isSuccess: Boolean,
    errorMsg: String,
    response: NetworkResponse
): Response<T> {
    val obj = Response<T>().apply {
        success = isSuccess
        msg = errorMsg
        code = response.statusCode ?: HttpRequestCode.CODE_REQUEST_SUCCESS.value
    }
    return obj
}

suspend inline fun <reified T> post(
    url: String,
    param: JSONObject = JSONObject(),
    headers: JSONObject = JSONObject()
): Response<T> {
    val networkModule = acquireNetworkModule()
    return suspendCoroutine { coroutine ->
        networkModule.httpRequest(
            url,
            true,
            param,
            pingCommonHead(headers),
            responseCallback = { json, isSuccess, errorMsg, response ->
                val obj = createResponse<T>(isSuccess, errorMsg, response)
                if (isSuccess) obj.data = Json.decodeFromString<T>(json.toString())
                coroutine.resume(obj)
            })
    }
}

fun acquireNetworkModule() = PagerManager.getCurrentPager()
    .acquireModule<NetworkModule>(NetworkModule.MODULE_NAME)